import os
from PIL import Image
import tkinter as tk
import tkinter.filedialog as dlg 
import tkinter.messagebox as msgbox


class MainWindow(tk.Tk):
    def __init__(self):
        super().__init__()
        self.filename = tk.StringVar()
        self.filename.set("")
        self.threshold = tk.IntVar()
        self.threshold.set(160)
        self.InitGI()

    def InitGI(self):
        self.title("黑白图像")
        tk.Label(self, text="文件:").grid(row=0,column=0,sticky="e")
        tk.Entry(self, width=40, textvariable=self.filename).grid(row=0,column=1,sticky="e"+"w")
        tk.Button(self,text="选择", command=self.select_filename).grid(row=0,column=2, sticky="e"+"w", pady=20)
        tk.Label(self, text="阈值:").grid(row=1,column=0,sticky="e")
        tk.Entry(self, width=12, textvariable=self.threshold).grid(row=1,column=1,sticky="w")
        tk.Button(self, text="黑白图像", 
                command=self.blackwhite_image).grid(row=1,column=2,pady=10)

    def select_filename(self):
        types =[("All Files","*"), ("图片jpeg文件","*.jpeg"), ("图片jpg文件","*.jpg"), ("图片png文件","*.png") ]
        filename = dlg.askopenfilename(title="打开图片文件", defaultextension=".jpg",  filetypes=types)
        self.filename.set(filename)

    def blackwhite_image(self):
        filename = self.filename.get()
        threshold = self.threshold.get()
        if not filename:
            msgbox.showinfo("图片处理", "图片文件没有选择!")
            return
        image = Image.open(filename)
        gray = image.convert("L")
        binary = gray.point(lambda x: 255 if x>threshold else x)
        dir = os.path.dirname(filename)
        name = os.path.basename(filename)
        temppath = os.path.join(dir,"黑白_"+name)
        binary.save(temppath)
        msgbox.showinfo("图片处理", f"黑白处理 {filename} 成功!")


def run():
    win = MainWindow()
    win.mainloop()

if __name__ == '__main__':
    run()